package org.jeecg.modules.demo.mp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.mp.entity.MpMasterplan;
import org.jeecg.modules.demo.mp.entity.MpMasterplanUpload;
import org.jeecg.modules.demo.mp.entity.MpMasterplanUploadHis;
import org.jeecg.modules.demo.mp.service.IMpMasterplanService;
import org.jeecg.modules.demo.mp.service.IMpMasterplanUploadHisService;
import org.jeecg.modules.demo.mp.service.IMpMasterplanUploadService;
import org.jeecg.modules.demo.mp.util.MPParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: Budget Upload
 * @Author: jeecg-boot
 * @Date: 2022-06-30
 * @Version: V1.0
 */
@Api(tags = "Budget Upload")
@RestController
@RequestMapping("/mp/mpMasterplanUpload")
@Slf4j
public class MpMasterplanUploadController extends JeecgController<MpMasterplanUpload, IMpMasterplanUploadService> {
    @Autowired
    private IMpMasterplanUploadService mpMasterplanUploadService;
    @Autowired
    private IMpMasterplanService mpMasterplanService;
    @Autowired
    private IMpMasterplanUploadHisService mpMasterplanUploadHisService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 本地：local minio：minio 阿里：alioss
     */
    @Value(value = "${jeecg.uploadType}")
    private String uploadType;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;


    /**
     * 分页列表查询
     *
     * @param mpMasterplanUpload
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "Budget Upload-分页列表查询")
    @ApiOperation(value = "Budget Upload-分页列表查询", notes = "Budget Upload-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MpMasterplanUpload>> queryPageList(MpMasterplanUpload mpMasterplanUpload,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        QueryWrapper<MpMasterplanUpload> queryWrapper = QueryGenerator.initQueryWrapper(mpMasterplanUpload, req.getParameterMap());
        Page<MpMasterplanUpload> page = new Page<MpMasterplanUpload>(pageNo, pageSize);
        IPage<MpMasterplanUpload> pageList = mpMasterplanUploadService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mpMasterplanUpload
     * @return
     */
    @AutoLog(value = "Budget Upload-添加")
    @ApiOperation(value = "Budget Upload-添加", notes = "Budget Upload-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MpMasterplanUpload mpMasterplanUpload) {
        mpMasterplanUploadService.save(mpMasterplanUpload);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mpMasterplanUpload
     * @return
     */
    @AutoLog(value = "Budget Upload-编辑")
    @ApiOperation(value = "Budget Upload-编辑", notes = "Budget Upload-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MpMasterplanUpload mpMasterplanUpload) {
        mpMasterplanUploadService.updateById(mpMasterplanUpload);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "Budget Upload-通过id删除")
    @ApiOperation(value = "Budget Upload-通过id删除", notes = "Budget Upload-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        mpMasterplanUploadService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "Budget Upload-批量删除")
    @ApiOperation(value = "Budget Upload-批量删除", notes = "Budget Upload-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mpMasterplanUploadService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "Budget Upload-通过id查询")
    @ApiOperation(value = "Budget Upload-通过id查询", notes = "Budget Upload-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MpMasterplanUpload> queryById(@RequestParam(name = "id", required = true) String id) {
        MpMasterplanUpload mpMasterplanUpload = mpMasterplanUploadService.getById(id);
        if (mpMasterplanUpload == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mpMasterplanUpload);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mpMasterplanUpload
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MpMasterplanUpload mpMasterplanUpload) {
        return super.exportXls(request, mpMasterplanUpload, MpMasterplanUpload.class, "Budget Upload");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MpMasterplanUpload.class);
    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelByDivision", method = RequestMethod.POST)
    public Result<?> importExcelByDivision(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = "masterplan";

        //LOWCOD-2580 sys/common/upload接口存在任意文件上传漏洞
        if (oConvertUtils.isNotEmpty(bizPath) && (bizPath.contains("../") || bizPath.contains("..\\"))) {
            throw new JeecgBootException("上传目录bizPath，格式非法！");
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        Map<String, MultipartFile> filesMap = multipartRequest.getFileMap();
        String recordId = (String) (filesMap.keySet().toArray())[0];

        // 获取上传文件对象
        MultipartFile file = multipartRequest.getFile(recordId);
        if (oConvertUtils.isEmpty(bizPath)) {
            bizPath = "";
        }

        // local本地保存
        savePath = CommonUtils.uploadLocal(file, bizPath, uploadpath);
        if (oConvertUtils.isNotEmpty(savePath)) {
            StringBuilder msg = new StringBuilder();
            result.setMessage(savePath);
            result.setSuccess(true);

            MpMasterplanUpload vo = mpMasterplanUploadService.getBaseMapper().selectById(recordId);
            //获取当前版本
            String currVersion;
            if (vo == null) {
                currVersion = getCurrVersion("MasterPlan");
                if (currVersion == null) {
                    throw new JeecgBootException("请设置MasterPlan的工作版本！");
                }
            } else {
                currVersion = vo.getVersion();
            }

            //  解析预算数据
            List<MpMasterplan> mpList = null;
            try {
                mpList = MPParser.parseMasterPlan(file.getInputStream(), currVersion);
            } catch (Exception e) {
                e.printStackTrace();
            }
            msg.append("解析返回").append(mpList.size()).append("条");

            if (mpList != null && !mpList.isEmpty()) {
//                删掉非当期的记录
                mpList.removeIf(mp -> !currVersion.equals(mp.getVersion()));

                if (mpList.isEmpty()) {
                    result.setMessage("未检索到" + currVersion + "的记录");

                    return result;
                }

                msg.append(",当期数据").append(mpList.size()).append("条");

                // 提取数据不为空

                QueryWrapper<MpMasterplanUpload> queryWrapper = new QueryWrapper<MpMasterplanUpload>();
                queryWrapper.eq("version", currVersion);
//				 queryWrapper.in("division",bgByDivision.keySet());
                List<MpMasterplanUpload> uploadList = mpMasterplanUploadService.list(queryWrapper);
                List<MpMasterplanUploadHis> uploadHisList = new ArrayList<MpMasterplanUploadHis>();

                MpMasterplanUpload e = null;
                if (!uploadList.isEmpty()) {
                    e = uploadList.get(0);
                } else {
                    e = new MpMasterplanUpload();
                    e.setVersion(currVersion);
                    e.setRevision(0);
                    uploadList.add(e);
                }
//                    更新版本信息
                e.setFiles(savePath);
                e.setFileName(file.getOriginalFilename());
//TODO                    增加版本变动数据说明
                e.setComment("本次更新" + mpList.size() + "条");
                // 版本+1
                e.setRevision(e.getRevision() + 1);

                MpMasterplanUploadHis eHis = copyToUploadHis(e);
                uploadHisList.add(eHis);

                mpMasterplanUploadService.saveOrUpdateBatch(uploadList);
                mpMasterplanUploadHisService.saveOrUpdateBatch(uploadHisList);

//					 TODO 增加版本控制
                for (MpMasterplan mp : mpList) {
                    mp.setRevision(e.getRevision());
                    // 记录版本号
                    mp.setBatchid(e.getId());
                }


//               相同数据维度，更新原纪录的ID和createtime
                QueryWrapper<MpMasterplan> queryWrapper4Mp = new QueryWrapper<MpMasterplan>();
                queryWrapper4Mp.eq("version", currVersion);
                List<MpMasterplan> dbBgList = mpMasterplanService.list(queryWrapper4Mp);
                Map<String, MpMasterplan> dbMpMap = new HashMap<String, MpMasterplan>();
                for (MpMasterplan bg : dbBgList) {
                    dbMpMap.put(bg.getDimKey(), bg);
                }
                for (MpMasterplan mp : mpList) {
                    if (dbMpMap.containsKey(mp.getDimKey())) {
                        MpMasterplan dbBg = dbMpMap.get(mp.getDimKey());
                        mp.setCreateBy(dbBg.getCreateBy());
                        mp.setCreateTime(dbBg.getCreateTime());
                        mp.setId(dbBg.getId());
                    }

                }


                mpMasterplanService.saveOrUpdateBatch(mpList);


                // TODO  生成历史记录

                result.setMessage(msg.toString());
            }


        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }


    private MpMasterplanUploadHis copyToUploadHis(MpMasterplanUpload mp) {
        MpMasterplanUploadHis mpHis = new MpMasterplanUploadHis();
        mpHis.setBatchid(mp.getId());
        mpHis.setCreateBy(mp.getCreateBy());
        mpHis.setCreateTime(mp.getCreateTime());
        mpHis.setUpdateBy(mp.getUpdateBy());
        mpHis.setUpdateTime(mp.getUpdateTime());
        mpHis.setVersion(mp.getVersion());
//        mpHis.setDivision(mp.getDivision());
        mpHis.setRevision(mp.getRevision());
        mpHis.setFiles(mp.getFiles());
        mpHis.setFileName(mp.getFileName());
        mpHis.setComment(mp.getComment());

        return mpHis;
    }

    private String getCurrVersion(String typ) {
        String currVersion;
        String sql = "SELECT version FROM mp_period where typ='" + typ + "' and iscurrent=1";
        currVersion = jdbcTemplate.queryForObject(sql, String.class);
        return currVersion;
    }
}
